import 'dart:async';
import 'dart:io';

import 'package:flutter_cache_manager/flutter_cache_manager.dart';

import 'package:isolate_manager/isolate_manager.dart';

class LyCacheManager {
  // static LyCacheManager? _install;
  // static LyCacheManager get install => _install ?? LyCacheManager._();
  // LyCacheManager._();

  static const key = 'ly_cache_key';
  static final CacheManager _instance = CacheManager(
    Config(
      key,
      stalePeriod: const Duration(days: 7),
      maxNrOfCacheObjects: 20,
      repo: JsonCacheInfoRepository(databaseName: key),
      // fileSystem: IOFileSystem(key),
      fileService: HttpFileService(),
    ),
  );
  static final _isolateFetchAndDecode = IsolateManager.create(
    fetchAndDecode, // Function you want to compute
    concurrent: 3, // Number of concurrent isolates. Default is 1
  )..start();

  static Future downloadFiles(List<String> urls) async {
    for (var element in urls) {
      addIsolateTask(element);
    }
  }

  static Stream get isolateStream => _isolateFetchAndDecode.stream;

  static Future addIsolateTask(String url) {
    return _isolateFetchAndDecode.compute(url);
  }

  static stopIsolate() {
    _isolateFetchAndDecode.stop();
  }

  static disposs() {
    _instance.dispose();
    stopIsolate();
  }

  static cleanCache() {
    _instance.emptyCache();
  }

  static Future<FileInfo> downloadFile(String url) {
    return _instance.downloadFile(url);
  }

  static Future<File> getSingleFile(String url) {
    return _instance.getSingleFile(url);
  }
}

@isolateManagerWorker
Future fetchAndDecode(String url) async {
  return LyCacheManager.downloadFile(url);
}
